import AuthAPI, { type LoginData } from "@/api/auth";
import UserAPI, { type UserInfo } from "@/api/user";
import { resetRouter } from "@/router";
import { store } from "@/store";
import { TOKEN_KEY } from "@/enums/CacheEnum";

export const useUserStore = defineStore("user", () => {
  const user = ref<UserInfo>({
    roles: [],
    perms: [],
  });

  /**
   * 登录
   *
   * @param {LoginData}
   * @returns
   */
  // function login(loginData: LoginData) {
  //   return new Promise<void>((resolve, reject) => {
  //     // 登录接口调用
  //     AuthAPI.login(loginData)
  //       .then((data) => {
  //         const { accessToken } = data;
  //         let tokenType = "Bearer";
  //         localStorage.setItem(TOKEN_KEY, tokenType + " " + accessToken); // Bearer eyJhbGciOiJIUzI1NiJ9.xxx.xxx
  //         resolve();
  //       })
  //       .catch((error) => {
  //         reject(error);
  //       });
  //   });
  // }
  function login(loginData: LoginData) {
    return new Promise<void>((resolve) => {
      // 使用假数据代替真实的登录接口调用
      const fakeToken = "fakeAccessToken"; // 这里是假的 accessToken，可以根据需要修改
      const tokenType = "Bearer";
      localStorage.setItem(TOKEN_KEY, `${tokenType} ${fakeToken}`); // 存储为 "Bearer fakeAccessToken"

      // 假设登录成功，直接 resolve
      resolve();
    });
  }

  // 获取信息(用户昵称、头像、角色集合、权限集合)
  // function getUserInfo() {
  //   return new Promise<UserInfo>((resolve, reject) => {
  //     UserAPI.getInfo()
  //       .then((data) => {
  //         if (!data) {
  //           reject("Verification failed, please Login again.");
  //           return;
  //         }
  //         if (!data.roles || data.roles.length <= 0) {
  //           reject("getUserInfo: roles must be a non-null array!");
  //           return;
  //         }
  //         Object.assign(user.value, { ...data });
  //         resolve(data);
  //       })
  //       .catch((error) => {
  //         reject(error);
  //       });
  //   });
  // }
  const staticUserInfo = {
    userId: 2,
    nickname: "系统管理员",
    username: "admin",
    avatar:
      "https://foruda.gitee.com/images/1723603502796844527/03cdca2a_716974.gif?imageView2/1/w/80/h/80",
    roles: ["ROOT"],
    perms: [
      "sys:menu:delete",
      "sys:dept:edit",
      "sys:dict_type:add",
      "sys:dict:edit",
      "sys:dict:delete",
      "sys:dict_type:edit",
      "sys:menu:add",
      "sys:user:add",
      "sys:role:edit",
      "sys:dept:delete",
      "sys:user:edit",
      "sys:user:delete",
      "sys:user:password:reset",
      "sys:dept:add",
      "sys:role:delete",
      "sys:dict_type:delete",
      "sys:menu:edit",
      "sys:dict:add",
      "sys:role:add",
      "sys:user:query",
      "sys:user:export",
      "sys:user:import",
    ],
  };

  function getUserInfo() {
    return new Promise((resolve) => {
      // 直接使用静态数据而不是调用接口
      Object.assign(user.value, { ...staticUserInfo });
      resolve(staticUserInfo);
    });
  }

  // user logout
  // function logout() {
  //   console.log("logout");

  //   return new Promise<void>((resolve, reject) => {
  //     AuthAPI.logout()
  //       .then(() => {
  //         localStorage.setItem(TOKEN_KEY, "");
  //         location.reload(); // 清空路由
  //         resolve();
  //       })
  //       .catch((error) => {
  //         reject(error);
  //       });
  //   });
  // }
  // user logout
  function logout() {
    console.log("logout");

    return new Promise<void>((resolve) => {
      // 不调用 AuthAPI.logout() 接口
      localStorage.setItem(TOKEN_KEY, "");
      location.reload(); // 清空路由
      resolve();
    });
  }

  // remove token
  function resetToken() {
    return new Promise<void>((resolve) => {
      localStorage.setItem(TOKEN_KEY, "");
      resetRouter();
      resolve();
    });
  }

  return {
    user,
    login,
    getUserInfo,
    logout,
    resetToken,
  };
});

/**
 * 用于在组件外部（如在Pinia Store 中）使用 Pinia 提供的 store 实例。
 * 官方文档解释了如何在组件外部使用 Pinia Store：
 * https://pinia.vuejs.org/core-concepts/outside-component-usage.html#using-a-store-outside-of-a-component
 */
export function useUserStoreHook() {
  return useUserStore(store);
}
